package com.alexsh.dao.impl;

import au.com.bytecode.opencsv.CSVReader;
import com.alexsh.dao.DataLoader;
import com.alexsh.domain.Book;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author Alexander Shmygin <AShmygin@luxoft.com>
 * @version 1.0
 */
public class CsvFileLoader implements DataLoader {

    private static final Log logger = LogFactory.getLog(CsvFileLoader.class);

    private static final String DEFAULT_ENCODING = "US-ASCII";
    private static final char DEFAULT_COL_DELIMITER = ';';
    private static final char DEFAULT_TEXT_QUALIFIER = '"';
    private static final int LINE_NUMBER_TO_SKIP = 1;

    private static final int INT_1 = 1;
    private static final int INT_2 = 2;
    private static final int INT_3 = 3;

    private static final ResourceBundle APP_BUNDLE = ResourceBundle.getBundle("app");

    private static final SimpleDateFormat SDF = new SimpleDateFormat(
        "MM/dd/yyyy");


    public HashMap<String, Book> getData() {
        HashMap<String, Book> books = new HashMap<String, Book>();
        InputStream inputStream = BooksRepository.class.getClassLoader()
            .getResourceAsStream("repository/" + APP_BUNDLE.getString("data.booksFile"));
        try {
            InputStreamReader isr = new InputStreamReader(inputStream, DEFAULT_ENCODING);
            CSVReader csvReader = new CSVReader(isr, DEFAULT_COL_DELIMITER,
                DEFAULT_TEXT_QUALIFIER, LINE_NUMBER_TO_SKIP);
            List<String[]> csvRows = csvReader.readAll();
            populateBooks(books, csvRows);
        } catch (UnsupportedEncodingException e) {
            logger.error("The Character Encoding is not supported.", e);
        } catch (IOException e) {
            logger.error("Can't read CSV file.", e);
        } catch (ParseException e) {
            logger.error("Can't parse date.", e);
        }
        return books;
    }

    private void populateBooks(HashMap<String, Book> books, List<String[]> csvRows)
        throws ParseException {
        Book book;
        for (String[] row : csvRows) {
            book = new Book();
            book.setId(row[0]);
            book.setTitle(row[INT_1]);
            book.setAuthors(row[INT_2]);
            book.setPubDate(SDF.parse(row[INT_3]));
            books.put(book.getId(), book);
        }
    }
}
